'''
Author: thinktanker thinktanker@163.com
Date: 2024-03-11 15:00:16
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2024-03-11 15:00:21
FilePath: \llj\allwindows.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import win32gui


# def enum_callback(hwnd, lParam):
#     # 过滤条件，例如检查窗口是否可见并且有效
#     if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
#         title = win32gui.GetWindowText(hwnd)
#         # 将标题转换为UTF-8编码（如果需要的话，根据实际编码环境调整）
#         try:
#             title_utf8 = title.encode('utf-8')
#         except UnicodeError:
#             title_utf8 = title.encode('gbk')  # 对于非Unicode标题尝试GBK编码
#         print(f'窗口句柄：{hwnd} | 窗口标题：{title_utf8.decode()}')


def enum_child_callback(child_hwnd, param):
    child_title = win32gui.GetWindowText(child_hwnd)
    print(f'子窗口句柄：{child_hwnd} | 子窗口标题：{child_title}')


# 在遍历顶层窗口时添加子窗口遍历
def enum_callback(hwnd, lParam):
    # ...
    if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        # 输出顶层窗口信息
        title = win32gui.GetWindowText(hwnd)
        # 将标题转换为UTF-8编码（如果需要的话，根据实际编码环境调整）
        try:
            title_utf8 = title.encode('utf-8')
        except UnicodeError:
            title_utf8 = title.encode('gbk')  # 对于非Unicode标题尝试GBK编码
        print(f'窗口句柄：{hwnd} | 窗口标题：{title_utf8.decode()}')

        # print(f'窗口句柄：{hwnd} | 窗口标题：{title_utf8.decode()}')

        # 遍历子窗口
        win32gui.EnumChildWindows(hwnd, enum_child_callback, None)


# 调用EnumWindows函数遍历所有顶层窗口
win32gui.EnumWindows(enum_callback, None)
